# - Coding UTF8 -
#
# Networked Decision Making
# Site: http://code.google.com/p/global-decision-making-system/
#
# License Code: GPL, General Public License v. 2.0
# License Content: Creative Commons Attribution 3.0
#
# Also visit: www.web2py.com
#             or Groups: http://groups.google.com/group/web2py 
# 	For details on the web framework used for this development
#
# Developed by Russ King (newglobalstrategy@gmail.com
# Russ also blogs occasionally to pass the time at: 
# http://proudofyourplanent.blogspot.com
# His general thinking on why this project is very important is available at
# http://www.scribd.com/doc/98216626/New-Global-Strategy
# With thanks to Guido, Massimo and many other that make this sort of thing
# much easier than it used to be


# 4 Functions included here
# index - allows viewing of all actions
# keymail - allows generating standard message to send to global leaders
# stdmsg - displays the generated message
# sendmsg - actually sends via ajax


def index():
    fields= ['sortorder','showscope','scope', 'continent','country',
             'subdivision','showcat','category']
    form = SQLFORM(db.viewscope, fields=fields)
    page = 0
    q = 'Act'
    s = 'Pr'

    if session.showscope is None:
        form.vars.showscope = False
        form.vars.showcat = False
    else:
        form.vars.showscope = session.showscope
        form.vars.showcat = session.showcat
        form.vars.category = session.category
        form.vars.scope = session.scope
        form.vars.continent = session.vwcontinent
        form.vars.country = session.vwcountry
        form.vars.subdivision = session.vwsubdivision
    
    if session.sortorder is not None:
        form.vars.sortorder = session.sortorder

    if len(request.args): 
        page=int(request.args[0])
        if len(request.args)>1:
            q = request.args[1]
            if len(request.args)>2:
                s = request.args[2]
    else: page=0

    items_per_page=20
    limitby=(page*items_per_page,(page+1)*items_per_page+1)

    if session.sortorder is not None:   
        if session.sortorder == '1 Priority':
            s = 'Priority'
        elif session.sortorder == '2 Due Date':
            s = 'Due'
        elif session.sortorder == '3 Resolved Date':
            s = 'Resolved'
        elif session.sortorder == '4 Submit Date':
            s = 'Submit'
        elif session.sortorder == '5 Responsible':
            s = 'Responsible'

    if form.validate():
        session.showcat = form.vars.showcat
        session.showscope = form.vars.showscope
        session.scope = form.vars.scope
        session.category = form.vars.category
        session.vwcontinent = form.vars.continent
        session.vwcountry = form.vars.country
        session.vwsubdivision = form.vars.subdivision
        session.sortorder = form.vars.sortorder
 
        if session.sortorder == '1 Priority':
            s = 'Priority'
        elif session.sortorder == '2 Due Date':
            s = 'Due'
        elif session.sortorder == '3 Resolved Date':
            s = 'Resolved'
        elif session.sortorder == '4 Submit Date':
            s = 'Submit'
        elif session.sortorder == '5 Responsible':
            s = 'Responsible'

        page = 0
        redirect(URL('index',args=[page,q,s]))  


    # Actions can be selected for all or status of Agreed, In Progress or Disagreed
    # Rejected actions cannot be reviewed
    query = (db.question.qtype == 'action')

    if q == 'Agreed':
        query = (db.question.qtype == 'action') & (db.question.status == 'Agreed')
    elif q == 'Proposed':
        query = (db.question.qtype == 'action') & (db.question.status == 'In Progress')
    elif q == 'Disagreed':
        query = (db.question.qtype == 'action') & (db.question.status == 'Disagreed')
    elif q == 'My' and auth.user is not None:
        query = (db.question.qtype == 'action') & (db.question.auth_userid == auth.user.id)


    if session.showcat == True:
        query = query & (db.question.category == session.category)
    if session.showscope == True:
        if session.scope == "1 Global":
            query = query & (db.question.activescope == session.scope)   
        elif session.scope == "2 Continental":
            query = query & (db.question.activescope == session.scope) & (
            db.question.continent == session.vwcontinent)
        elif session.scope == "3 National":
            query = query & (db.question.activescope == session.scope) & (
            db.question.country == session.vwcountry)
        elif session.scope == "4 Local":
            query = query & (db.question.activescope == session.scope) & (
            db.question.subdivision == session.vwsubdivision)

    # And they can be sorted by create date, priority and due date    
    # not got a control for this yet probably part of request.args
    sortby = ~db.question.priority
    if s == 'Due':
        sortby = db.question.duedate
    elif s == 'Create':
        sortby = ~db.question.createdate
    elif s == 'Resolved':
        sortby = ~db.question.resolvedate
    elif s == 'Responsible':
        sortby = db.question.responsible
  


    actions = db(query).select(
                 db.question.id, db.question.status, db.question.questiontext, db.question.duedate,
                 db.question.responsible, db.question.priority, db.question.achieved,
                 db.question.activescope, db.question.category, db.question.continent, 
                 db.question.country, db.question.subdivision, db.question.scopetext,
                 orderby=sortby,limitby=limitby)


    return dict(form=form, actions=actions,page=page,items_per_page=items_per_page,q=q,s=s,query=query)


def keymail():
    countries = db(db.country.isg20 == True).select(db.country.id, db.country.country_name, 
                   db.country.leader, orderby=db.country.country_name)

    companies = db(db.company.id>0).select(db.company.id, db.company.company_name, 
                   db.company.leader,  orderby=db.company.company_name)

    people = db(db.individual.id>0).select(db.individual.id, db.individual.leader,
                                           orderby=db.individual.leader)
    return dict(countries=countries, companies=companies, people=people)

def stdmsg():
    rowid = request.args[1]
    if request.args[0] == 'country':
        leader = db(db.country.id == rowid).select(db.country.leader,
                    db.country.email, db.country.contact_method,
                    db.country.website).first()
    elif request.args[0] == 'company':
        leader = db(db.company.id == rowid).select(db.company.leader,
                    db.company.contact_method,db.company.email,
                    db.company.website).first()
    else:
        leader = db(db.individual.id == rowid).select(db.individual.leader,
                    db.individual.contact_method, db.individual.email,
                    db.individual.website).first()

    message = db(db.message.msgtype == 'std').select(db.message.message_text).first()

    return dict(leader=leader,message=message,source=request.args[0],rowid=rowid)

def sendmsg():
    #Called via ajax to send messages to users for forwarding on as they see fit
    if auth.user == None:
        responsetext = 'You must be logged in to create messages'
    else:
        messagetxt = db(db.message.msgtype == 'std').select(
                        db.message.message_text).first().message_text
    
        email=[auth.user.email]

        link = URL('default','index', scheme=True, host=True)
        #link = URL('viewquest','index', args=questid, scheme=True, host=True)
        footnote = 'More details on the overall approach and the identified actions can be found at: '+ link
        #messagetxt = '<html>' + messagetxt + ' ' + footnote + '</html>'   
        messagetxt = messagetxt + ' ' + footnote
        mail.send(to=email,
        subject='Networked Decision Making Action Request',
        message=messagetxt)

        responsetext = 'Your message has been sent to you to foward on.'

    return responsetext

